package com.CST.service.impl.ys;

import com.CST.common.api.ResultObject;
import com.CST.entity.ys.YsAppealRecord;
import com.CST.entity.ys.YsFileUpload;
import com.CST.mapper.cst.ys.YsAppealRecordMapper;
import com.CST.mapper.cst.ys.YsFileUploadMapper;
import com.CST.service.ys.FileService;
import com.CST.util.FileUtils;

import com.CST.util.UploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class FileServiceImp implements FileService {
    private final YsAppealRecordMapper dao;
    private final YsFileUploadMapper fileDao;
    @Value("${upload}")
    private String filePath;
    public FileServiceImp(YsAppealRecordMapper dao, YsFileUploadMapper fileDao) {
        this.dao = dao;
        this.fileDao = fileDao;
    }
    @Override
    public void download(Long id, HttpServletResponse response) throws IOException {
        YsAppealRecord record = dao.selectById(id);
        Optional.ofNullable(record).orElseThrow(()->new RuntimeException("该条申诉内容不存在"));
        //获取文件地址

        List<YsFileUpload> fileUpload = fileDao.selectBatchIds(Arrays.asList(record.getFileAddr()
                .split(";")));
        String[] urls = fileUpload.stream().map(YsFileUpload::getUuidName).toArray(String[]::new);
        String[] names = fileUpload.stream().map(YsFileUpload::getFileName).toArray(String[]::new);
        HashMap<String,Integer> map = new HashMap<>();
        if(urls.length>0){
            ZipOutputStream zipOutputStream = null;
            InputStream []srcFile = new InputStream[urls.length];
           try{
               zipOutputStream = new ZipOutputStream(response.getOutputStream());
               //设置 response 响应类型
               response.reset();
               response.setContentType("application/octet-stream");
               response.setHeader("Content-Disposition", "attachment;filename=" +
                       URLEncoder.encode(new SimpleDateFormat("yyyyMMddhhmmss").
                               format(new Date())+ ".zip", "UTF-8"));
               //遍历每一个文件，放入压缩包中

               for (int i=0;i<urls.length;i++) {
                   File file = new File(filePath+urls[i]);
                   srcFile[i] = Files.newInputStream(file.toPath());
                   String num = "";
                   if (map.containsKey(names[i])) {
                       map.put(names[i], map.get(names[i]) + 1);
                       num = "(" + map.get(names[i]) + ")";
                   } else {
                       map.put(names[i], 1);
                   }
                   String[] type = names[i].split("\\.");

                   if(file.exists()){
                       ZipEntry zipEntry = new ZipEntry(type[0]+num+"."+type[1]);
                       zipOutputStream.putNextEntry(zipEntry);

                       byte[] buffer = new byte[1024];
                       int bytesRead = -1;
                       while ((bytesRead = srcFile[i].read(buffer)) > 0) {
                           zipOutputStream.write(buffer, 0, bytesRead);
                       }
                       srcFile[i].close();

                       zipOutputStream.closeEntry();
                   }
               }
           } finally {
               if (zipOutputStream!=null) {
                   try {
                       zipOutputStream.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
                   try {
                       zipOutputStream.flush();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
               try {
                   for (InputStream is : srcFile) {
                       is.close();
                   }
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }



    }


    @Override
    public YsFileUpload upload(MultipartFile files) throws IOException {
        String url = UploadUtils.uploadOne(files);
        YsFileUpload build = YsFileUpload.builder()
                .uuidName(url)
                .fileName(files.getOriginalFilename())
                .build();
        fileDao.insert(build);
        return build;
    }

}
